package com.xyh.reward_kotlin.fragments

import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.os.Bundle
import android.os.Environment
import android.util.Log
import android.view.View
import androidx.core.content.FileProvider
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.xyh.reward_kotlin.R
import com.google.android.material.snackbar.Snackbar
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.xyh.reward_kotlin.adapter.HistoryAdapter
import com.xyh.reward_kotlin.api.ApiCallback
import com.xyh.reward_kotlin.api.ApiClient
import com.xyh.reward_kotlin.api.RewardApi
import com.xyh.reward_kotlin.response.RewardResultDto
import androidx.core.content.edit
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.File
import java.io.FileOutputStream

class HistoryFragment : Fragment(R.layout.fragment_history) {

    private val rewardApi: RewardApi = ApiClient.client.create(RewardApi::class.java)
    private var recyclerView: RecyclerView? = null
    private var historyAdapter: HistoryAdapter? = null

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        Log.d("history", "onViewCreated: 初始化")

        recyclerView = view.findViewById(R.id.historyRecyclerView)
        recyclerView?.layoutManager = LinearLayoutManager(context)

        // 优先显示内存缓存
        if (!memoryCache.isNullOrEmpty()) {
            Log.d("history", "使用内存缓存，数量: ${memoryCache!!.size}")
            setupAdapter(memoryCache!!)
        } else {
            // 尝试加载本地缓存
            val localCache = loadCache()
            Log.d("history", "本地缓存数量: ${localCache.size}")
            if (localCache.isNotEmpty()) {
                memoryCache = localCache.toMutableList() // 同步到内存缓存
                setupAdapter(memoryCache!!)
            }
        }

        // 异步刷新数据
        Log.d("history", "准备发起网络请求刷新历史数据")
        rewardApi.getResult().enqueue(object : ApiCallback<List<RewardResultDto>>() {
            override fun onSuccess(result: List<RewardResultDto>) {
                Log.d("history", "网络请求成功，更新缓存，数量: ${result.size}")
                memoryCache = result.toMutableList()
                saveCache(result)
                if (historyAdapter == null) {
                    setupAdapter(memoryCache!!)
                } else {
                    historyAdapter?.updateData(result)
                }
            }

            override fun onError(errorMsg: String?) {
                Log.e("history", "加载历史数据失败: $errorMsg")
                Snackbar.make(view, "加载历史数据失败：$errorMsg", Snackbar.LENGTH_LONG).show()
            }
        })
    }

    /**
     * 初始化 adapter + 回调 + 手势
     */
    private fun setupAdapter(list: MutableList<RewardResultDto>) {
        historyAdapter = HistoryAdapter(requireContext(), list)
        recyclerView?.adapter = historyAdapter

        // 绑定回调
        historyAdapter?.onDeleteClick = { item ->
            historyAdapter?.removeItem(item)
            memoryCache?.remove(item) // ⚡ 同步更新内存缓存
            saveCache(memoryCache ?: emptyList()) // ⚡ 同步更新本地缓存
            Snackbar.make(requireView(), "已删除记录", Snackbar.LENGTH_SHORT).show()
        }

        historyAdapter?.onExportClick = { item ->
            lifecycleScope.launch(Dispatchers.IO) {
                withContext(Dispatchers.Main) {
                    Snackbar.make(requireView(), "正在下载 PDF...", Snackbar.LENGTH_INDEFINITE)
                        .show()
                }

                val file = downloadPdfFile(item.id)

                withContext(Dispatchers.Main) {
                    if (file != null) {
                        Snackbar.make(
                            requireView(),
                            "下载完成: ${file.absolutePath}",
                            Snackbar.LENGTH_LONG
                        ).show()
                        openPdf(file)
                    } else {
                        Snackbar.make(requireView(), "下载失败", Snackbar.LENGTH_SHORT).show()
                    }
                }
            }
        }

        historyAdapter?.onPinClick = { item ->
            historyAdapter?.pinItem(item)
            Snackbar.make(requireView(), "已置顶", Snackbar.LENGTH_SHORT).show()
        }
    }


    private suspend fun downloadPdfFile(id: Long): File? {
        val call = rewardApi.downloadPdf(id)
        return try {
            val response = call.execute()
            if (response.isSuccessful) {
                response.body()?.let { body ->
                    val file = File(
                        requireContext().getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS),
                        "reward_${id}.pdf"
                    )
                    body.byteStream().use { input ->
                        FileOutputStream(file).use { output ->
                            val buffer = ByteArray(8192)
                            var bytesRead: Int
                            while (input.read(buffer).also { bytesRead = it } != -1) {
                                output.write(buffer, 0, bytesRead)
                            }
                            output.flush()
                        }
                    }
                    file
                }
            } else null
        } catch (e: Exception) {
            null
        }
    }

    private fun openPdf(file: File) {
        val uri = FileProvider.getUriForFile(
            requireContext(),
            "${requireContext().packageName}.fileprovider",
            file
        )
        val intent = Intent(Intent.ACTION_VIEW).apply {
            setDataAndType(uri, "application/pdf")
            addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
        }
        startActivity(Intent.createChooser(intent, "打开 PDF"))
    }

    // 保存到本地缓存
    private fun saveCache(list: List<RewardResultDto>) {
        Log.d("history", "保存本地缓存，数量: ${list.size}")
        val prefs: SharedPreferences = requireContext().getSharedPreferences(
            "history_cache",
            Context.MODE_PRIVATE
        )
        prefs.edit {
            putString("data", Gson().toJson(list))
        }
    }

    // 从本地缓存读取
    private fun loadCache(): List<RewardResultDto> {
        val prefs: SharedPreferences = requireContext().getSharedPreferences(
            "history_cache",
            Context.MODE_PRIVATE
        )
        val json: String? = prefs.getString("data", null)
        Log.d("history", "读取本地缓存 json: $json")
        return if (json != null) {
            val listType = object : TypeToken<List<RewardResultDto>>() {}.type
            Gson().fromJson(json, listType)
        } else {
            emptyList()
        }
    }

    companion object {
        private var memoryCache: MutableList<RewardResultDto>? = null // 内存缓存
    }
}